package com.fafu.captcha.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import com.fafu.captcha.config.CaptchaProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private static Logger logger = LoggerFactory.getLogger(CaptchaController.class);
    @Autowired
    private CaptchaProperties cp;
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response,HttpSession session) throws IOException {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(cp.getWidth(), cp.getHeight());
        //确保在各个浏览器都都不会有变换, 固定发送格式是图片
        response.setContentType("image/jpeg");
        //不要缓存
        response.setHeader("Pragma", "No-cache");
        //图形验证码写出到浏览器 (工具文档有解释)
        lineCaptcha.write(response.getOutputStream());

        //打印在后台看
        Console.log(lineCaptcha.getCode());
        logger.info("logger生成的验证码内容: " + lineCaptcha.getCode());
        //存储一下
        session.setAttribute(cp.getSession().getKey(),lineCaptcha.getCode());
        session.setAttribute(cp.getSession().getDate(),new Date());
    }

    private long VALID_TIME_OUT = 60 * 1000;
    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session){
        //查看验证码是否为空
        if (!StringUtils.hasLength(captcha)){
            return false;
        }
        String saveCaptcha = (String) session.getAttribute(cp.getSession().getKey());
        Date saveDate = (Date) session.getAttribute(cp.getSession().getDate());
        if(captcha.equalsIgnoreCase(saveCaptcha) &&
                (saveDate != null || System.currentTimeMillis() - saveDate.getTime() < VALID_TIME_OUT)){
            return true;
        }
        return false;
    }
}
